﻿(async () => {
    await window.ris.initialize();
    let supportVideoDevicePlugin = !!ris.host;
    if (ris.host) {
        try {
            await ris.invokePlugin('VideoDevicePlugin', 'get-current-report-id', true, true);
        } catch {
            supportVideoDevicePlugin = false;
        }
    }
    $(() => {
        const $eventEmitter = $('body > .container');
        const $container = $('body > .container');
        const oid = getUrlSearch('oid');
        const opinion = "||无||";

        let isCapturing = null;

        let getReportEditing = () => $container.data('reportEditing');
        let getReportReadOnly = () => $container.data('reportReadOnly');

        const diagnosisTemplates = [];

        const replaceTemplate = (template) => {
            if (getReportEditing()) {
                if (template && !$.isEmptyObject(template)) {
                    let formData = form.getData();
                    let report = {
                        imageDiagnosis: template.imageDiagnosis,
                        imageOpinion: template.imageOpinion,
                        imageSeeing: template.imageSeeing
                    };
                    if (formData.report.imageOpinion === opinion) delete report.imageOpinion;
                    formData.report = { ...formData.report, ...report };
                    form.setData(formData);
                } else {
                    DevExpress.ui.notify('未选择模板', 'error');
                }
            }
        };
        const appendTemplate = (template) => {
            if (getReportEditing()) {
                let formData = form.getData();
                const report = formData.report;

                if (report.imageSeeing && template.imageSeeing) {
                    report.imageSeeing += '\r\n' + template.imageSeeing;
                } else {
                    report.imageSeeing = template.imageSeeing;
                }

                if (report.imageDiagnosis && template.imageDiagnosis) {
                    report.imageDiagnosis += '\r\n' + template.imageDiagnosis;
                } else {
                    report.imageDiagnosis = template.imageDiagnosis;
                }

                if (formData.report.imageOpinion !== opinion) {
                    if (report.imageOpinion && template.imageOpinion) {
                        report.imageOpinion += '\r\n' + template.imageOpinion;
                    } else {
                        report.imageOpinion = template.imageOpinion;
                    }
                }

                form.setData(formData);
            }
        };
        const saveTemplate = (template) => {
            let formData = form.getData();
            let report = {
                imageDiagnosis: formData.report.imageDiagnosis,
                imageOpinion: formData.report.imageOpinion,
                imageSeeing: formData.report.imageSeeing
            };
            if (formData.report.imageOpinion === opinion) delete report.imageOpinion;
            return {
                ...template, ...report
            }
        };

        let reportImageList, reportVideoList;

        renderImagePanel = ele => {
            reportImageList = $(ele).reportImageListWrapper({
                url: '/api/report-image-list',
                reportId: oid,
                importImages: async () => {
                    if (supportVideoDevicePlugin) {
                        if (isCapturing) {
                            try {
                                await ris.invokePlugin('VideoDevicePlugin', `import-images`, true, true);
                                DevExpress.ui.notify('导入图像文件成功', 'success');
                            } catch (error) {
                                DevExpress.ui.notify(error, 'error');
                            }
                        } else {
                            DevExpress.ui.notify('导入图像需要将当前报告设为采集状态', 'error');
                        }
                    }
                },
                exportImages: async images => {
                    if (ris.host) {
                        try {
                            const tempFile = await ris.host.writeFile(JSON.stringify(
                                images.map(image => {
                                    return {
                                        url: image.url,
                                        fileName: `${image.id}.jpg`
                                    }
                                })
                            ));
                            await ris.invokePlugin('ExportFilePlugin', `json remote "${tempFile}"`, true, true);
                            DevExpress.ui.notify('导出图像文件成功', 'success');
                        } catch (error) {
                            DevExpress.ui.notify(error, 'error');
                        }
                    }
                },
                invertImage: async image => {
                    if (ris.host) {
                        try {
                            let tempFile = await ris.host.writeFile(image);
                            await ris.invokePlugin('InvertImagePlugin', `"${tempFile}"`, true, true);
                            if (tempFile) {
                                const data = await ris.host.readFile(tempFile);
                                if (data) {
                                    return data;
                                }
                            }
                        } catch (error) {
                            DevExpress.ui.notify(error, 'error');
                        }
                    }
                }
            });

            if (supportVideoDevicePlugin) {
                window.report_detail_request_capturing_image_notification = (reportId, imageKey, imageFile) => {
                    if (reportId === oid && imageKey && imageFile) {
                        ris.host.readBase64(imageFile).then(base64 => {
                            reportImageList.addImages([{
                                id: imageKey,
                                data: base64
                            }]);
                        });
                    }
                };
                window.report_detail_image_stored_notification = (reportId, imageKey) => {
                    if (reportId === oid && imageKey) {
                        reportImageList.notificationImageStored({
                            id: imageKey
                        });
                    }
                };
            }

            reportImageList.setReadOnly(!getReportEditing());
            reportImageList.refresh();
        };

        renderVideoPanel = ele => {
            reportVideoList = $(ele).reportVideoListWrapper({
                url: '/api/report-video-list',
                reportId: oid,
                getVideos: async data => {
                    if (ris.host && data && data.id && data.date) {
                        try {
                            const tempFile = await ris.invokePlugin('VideoDevicePlugin', `get-video-files "${data.id}" "${data.date}"`, true, true);
                            if (tempFile) {
                                const content = await ris.host.readFile(tempFile);
                                if (content) {
                                    return JSON.parse(content);
                                }
                            }
                        } catch (error) {
                            DevExpress.ui.notify(error, 'error');
                        }
                    }
                    return [];
                },
                viewVideo: async video => {
                    if (ris.host) {
                        try {
                            await ris.invokePlugin('VideoDevicePlugin', `open-video-file "${video.file}" "${video.device}"`, true, true);
                        } catch (error) {
                            DevExpress.ui.notify(error, 'error');
                        }
                    }
                },
                importVideos: async data => {
                    if (ris.host && data && data.id && data.date) {
                        try {
                            await ris.invokePlugin('VideoDevicePlugin', `import-videos "${data.id}" "${data.date}"`, true, true);
                            DevExpress.ui.notify('导入视频文件成功', 'success');
                        } catch (error) {
                            DevExpress.ui.notify(error, 'error');
                        }
                    }
                },
                exportVideos: async videos => {
                    if (ris.host) {
                        try {
                            const tempFile = await ris.host.writeFile(JSON.stringify(
                                videos.map(video => video.file)
                            ));
                            await ris.invokePlugin('ExportFilePlugin', `json local "${tempFile}"`, true, true);
                            DevExpress.ui.notify('导出视频文件成功', 'success');
                        } catch (error) {
                            DevExpress.ui.notify(error, 'error');
                        }
                    }
                },
                deleteVideos: async videos => {
                    if (ris.host) {
                        try {
                            for (const video of videos) {
                                await ris.host.deleteFile(video.file);
                            }
                        } catch (error) {
                            DevExpress.ui.notify(error, 'error');
                        }
                    }
                },
            });

            if (supportVideoDevicePlugin) {
                window.report_detail_request_capturing_video_notification = reportId => {
                    if (reportId === oid) {
                        reportVideoList.refresh();
                    }
                };
            }

            reportVideoList.setReadOnly(!getReportEditing());
            reportVideoList.refresh();
        };

        renderTemplatePanel = ele => {
            $(ele).dxTabPanel({
                tabsPosition: 'bottom',
                iconPosition: 'start',
                items: [
                    {
                        title: '常用',
                        icon: '/icons/antd_file_text.svg',
                        template: '<div class="common-template-panel panel" />',
                    },
                    {
                        title: '个人',
                        icon: '/icons/antd_file_text.svg',
                        template: '<div class="personal-template-panel panel" />',
                    },
                    {
                        title: '科室',
                        icon: '/icons/antd_file_text.svg',
                        template: '<div class="department-template-panel panel" />',
                    },
                    {
                        title: '公共',
                        icon: '/icons/antd_file_text.svg',
                        template: '<div class="public-template-panel panel" />',
                    },
                ],
                onItemRendered: e => {
                    switch (e.itemData?.title) {
                        case '常用':
                            diagnosisTemplates.push($(e.itemElement).find('.panel').diagnosisTemplateWrapper({
                                url: '/api/diagnosis-template',
                                type: 'common',
                                reportId: oid,
                                allowNew: false,
                                allowEdit: false,
                                allowFilter: false,
                                allowCollapse: false,
                                allowClone: false,
                                replaceTemplate,
                                appendTemplate,
                            }));
                            break;
                        case '个人':
                            diagnosisTemplates.push($(e.itemElement).find('.panel').diagnosisTemplateWrapper({
                                url: '/api/diagnosis-template',
                                type: 'user',
                                reportId: oid,
                                allowCloneToUser: false,
                                allowCloneToPublic: false,
                                replaceTemplate,
                                appendTemplate,
                                saveTemplate
                            }));
                            break;
                        case '科室':
                            diagnosisTemplates.push($(e.itemElement).find('.panel').diagnosisTemplateWrapper({
                                url: '/api/diagnosis-template',
                                type: 'department',
                                reportId: oid,
                                allowCloneToDepartment: false,
                                allowCloneToPublic: false,
                                replaceTemplate,
                                appendTemplate,
                                saveTemplate
                            }));
                            break;
                        case '公共':
                            diagnosisTemplates.push($(e.itemElement).find('.panel').diagnosisTemplateWrapper({
                                url: '/api/diagnosis-template',
                                type: 'public',
                                reportId: oid,
                                allowNew: false,
                                allowEdit: false,
                                allowDelete: false,
                                allowCloneToPublic: false,
                                replaceTemplate,
                                appendTemplate,
                            }));
                            break;
                    }
                },
            });
        };

        renderHistoryPanel = ele => {
            const $ele = $('<div style="display: flex;flex-wrap: nowrap;flex-direction: column;height: 100%;"></ div>').appendTo(ele);
            let reloadGrid = () => {
                dataGrid1.refresh();
            };
            const toolbar1 = $('<div>').appendTo($ele).dxToolbar({}).dxToolbar('instance');
            const dataGrid1 = $('<div style="flex: 1;"><div />').appendTo($ele).dataGrid({
                id: 'report-detail-history-grid',
                key: 'oid',
                onLoad(loadOptions) {
                    return new Promise((resolve, reject) => {
                        $.post({
                            dataType: 'json',
                            contentType: 'application/json;charset=UTF-8',
                            url: `/api/report/get-exam-histories/${oid}`,
                            data: JSON.stringify(loadOptions),
                            success: result => {
                                if (result.success) {
                                    resolve(result)
                                } else {
                                    reject(result.error);
                                }
                            }
                        });
                    })
                },
            });
            const tools1 = $.getReportTools($eventEmitter, null, null, dataGrid1, null, null, {
                reloadGrid: () => {
                    if (reloadGrid instanceof Function) {
                        reloadGrid();
                    }
                }
            });
            toolbar1.option('items', [tools1.open, tools1.viewImage, tools1.refresh]);
        };

        renderFormPanel = ele => {
            const $ele = $('<div style="display: flex;flex-wrap: nowrap;flex-direction: column;height: 100%;"></ div>').appendTo(ele);
            let reloadGrid = () => {
                dataGrid1.refresh();
            };
            const toolbar1 = $('<div>').appendTo($ele).dxToolbar({}).dxToolbar('instance');
            const dataGrid1 = $('<div style="flex: 1;"><div />').appendTo($ele).dataGrid({
                id: 'report-detail-form-grid',
                key: 'oid',
                sorting: { mode: 'none' },
                onLoad(loadOptions) {
                    return new Promise((resolve, reject) => {
                        $.post({
                            dataType: 'json',
                            contentType: 'application/json;charset=UTF-8',
                            url: `/api/report/get-exam-forms/${oid}`,
                            data: JSON.stringify(loadOptions),
                            success: result => {
                                if (result.success) {
                                    resolve(result)
                                } else {
                                    reject(result.error);
                                }
                            }
                        });
                    })
                },
            });
            const tools1 = $.getReportTools($eventEmitter, null, null, dataGrid1, null, null, {
                reloadGrid: () => {
                    if (reloadGrid instanceof Function) {
                        reloadGrid();
                    }
                }
            });
            toolbar1.option('items', [tools1.refresh]);
        };

        renderEventPanel = ele => {
            const $ele = $('<div style="display: flex;flex-wrap: nowrap;flex-direction: column;height: 100%;"></ div>').appendTo(ele);
            let reloadGrid = () => {
                dataGrid1.refresh();
            };
            const toolbar1 = $('<div>').appendTo($ele).dxToolbar({}).dxToolbar('instance');
            const dataGrid1 = $('<div style="flex: 1;"><div />').appendTo($ele).dataGrid({
                id: 'report-detail-event-grid',
                key: 'oid',
                sorting: { mode: 'none' },
                onLoad(loadOptions) {
                    return new Promise((resolve, reject) => {
                        $.post({
                            dataType: 'json',
                            contentType: 'application/json;charset=UTF-8',
                            url: `/api/report/get-exam-events/${oid}`,
                            data: JSON.stringify(loadOptions),
                            success: result => {
                                if (result.success) {
                                    resolve(result)
                                } else {
                                    reject(result.error);
                                }
                            }
                        });
                    })
                },
            });
            const tools1 = $.getReportTools($eventEmitter, null, null, dataGrid1, null, null, {
                reloadGrid: () => {
                    if (reloadGrid instanceof Function) {
                        reloadGrid();
                    }
                }
            });
            toolbar1.option('items', [tools1.refresh]);
        };

        renderRemarkPanel = ele => {
            const $ele = $('<div style="display: flex;flex-wrap: nowrap;flex-direction: column;height: 100%;"></ div>').appendTo(ele);
            let reloadGrid = () => {
                dataGrid1.refresh();
            };
            const gridOperations = [];
            const toolbar1 = $('<div>').appendTo($ele).dxToolbar({}).dxToolbar('instance');
            const dataGrid1 = $('<div style="flex: 1;"><div />').appendTo($ele).dataGrid({
                id: 'report-detail-remark-grid',
                key: 'oid',
                sorting: { mode: 'none' },
                getOperations() {
                    //删除，更新
                    return gridOperations;
                },
                onLoad(loadOptions) {
                    return new Promise((resolve, reject) => {
                        $.post({
                            dataType: 'json',
                            contentType: 'application/json;charset=UTF-8',
                            url: `/api/report/get-exam-remarks/${oid}`,
                            data: JSON.stringify(loadOptions),
                            success: result => {
                                if (result.success) {
                                    resolve(result)
                                } else {
                                    reject(result.error);
                                }
                            }
                        });
                    })
                },
            });
            let formData = form.getData();
            const tools1 = $.getReportTools($eventEmitter, null, null, dataGrid1, null, null, {
                reloadGrid: () => {
                    if (reloadGrid instanceof Function) {
                        reloadGrid();
                    }
                },
                examId: formData.oid
            });
            if (getReportReadOnly()) {
                tools1.addRemark.visible = false;
                tools1.addRemark.disabled = true;
            } else {
                gridOperations.push(tools1.updateRemark, tools1.deleteRemark);
            }
            toolbar1.option('items', [tools1.addRemark, tools1.refresh]);
        };

        renderQueuingPanel = ele => {
            const $ele = $('<div style="display: flex;flex-wrap: nowrap;flex-direction: column;height: 100%;"></ div>').appendTo(ele);
            let reloadGrid = () => {
                dataGrid1.refresh();
            };
            const gridContextMenuItems = [];
            const toolbar1 = $('<div>').appendTo($ele).dxToolbar().dxToolbar('instance');
            const toolbar2 = $('<div>').appendTo($ele).dxToolbar().dxToolbar('instance');
            const dataGrid1 = $('<div style="flex: 1;"><div />').appendTo($ele).examGrid({
                id: 'report-detail-queuing-grid',
                key: 'oid',
                getContextMenuItems() {
                    return gridContextMenuItems;
                },
                onLoad(loadOptions) {
                    return new Promise((resolve, reject) => {
                        $.post({
                            dataType: 'json',
                            contentType: 'application/json;charset=UTF-8',
                            url: `/api/report/get-queues`,
                            data: JSON.stringify(loadOptions),
                            success: result => {
                                if (result.success) {
                                    resolve(result)
                                } else {
                                    reject(result.error);
                                }
                            }
                        });
                    })
                },
            });
            const tools1 = $.getReportTools($eventEmitter, null, null, dataGrid1, null, null, {
                reloadGrid: (f) => {
                    if (f instanceof Function) {
                        reloadGrid = f;
                    }
                    if (reloadGrid instanceof Function) {
                        reloadGrid();
                    }
                }
            });
            toolbar1.option('items', [tools1.start, tools1.callNext, tools1.call, tools1.refresh]);
            toolbar2.option('items', [tools1.queueStatus, tools1.wait, tools1.ready, tools1.skiped, tools1.pending, tools1.completed]);
            gridContextMenuItems.push(tools1.start, tools1.call, tools1.suspend, tools1.skip);
        };

        renderExamPanel = ele => {
            const $ele = $('<div style="display: flex;flex-wrap: nowrap;flex-direction: column;height: 100%;"></ div>').appendTo(ele);
            let reloadGrid = () => {
                dataGrid1.refresh();
            };
            const gridContextMenuItems = [];
            const toolbar1 = $('<div>').appendTo($ele).dxToolbar({}).dxToolbar('instance');
            //高级搜索
            const advancedSearch1 = $('<div class="advanced-search">').appendTo($ele).advancedSearchWithCollapse(null, (e) => {
                reloadGrid = () => {
                    dataGrid1.refresh({ userData: e });
                };
                reloadGrid();
            });
            $.get('/api/report/get-exam-advanced-search-view').then(result => {
                if (result.success) {
                    if (result.view) {
                        advancedSearch1.updateView(result.view, result.data);
                    }
                }
            });
            const dataGrid1 = $('<div style="flex: 1;"><div />').appendTo($ele).examGrid({
                id: 'report-detail-exam-grid',
                key: 'oid',
                getContextMenuItems() {
                    return gridContextMenuItems;
                },
                onLoad(loadOptions) {
                    return new Promise((resolve, reject) => {
                        $.post({
                            dataType: 'json',
                            contentType: 'application/json;charset=UTF-8',
                            url: `/api/report/get-exams`,
                            data: JSON.stringify(loadOptions),
                            success: result => {
                                if (result.success) {
                                    resolve(result)
                                } else {
                                    reject(result.error);
                                }
                            }
                        });
                    })
                },
            });
            const tools1 = $.getReportTools($eventEmitter, null, advancedSearch1, dataGrid1, null, null, {
                reloadGrid: (f) => {
                    if (f instanceof Function) {
                        reloadGrid = f;
                    }
                    if (reloadGrid instanceof Function) {
                        reloadGrid();
                    }
                }
            });
            tools1.print.options.items = [tools1.formalPrint.options, tools1.temporarilyPrint.options];
            toolbar1.option('items', [tools1.reportQuickFilter, {
                ...tools1.open, options: {
                    ...tools1.open.options,
                    text: '打开',
                }
            }, {
                ...tools1.write, options: {
                    ...tools1.write.options,
                    text: '书写',
                }
            }, {
                ...tools1.audit, options: {
                    ...tools1.audit.options,
                    text: '审核',
                }
            }, tools1.refresh]);
            gridContextMenuItems.push(tools1.open, tools1.viewImage, tools1.write, tools1.audit, tools1.printReport, tools1.printReport2, tools1.markFollowUp,
                tools1.followUpRecord, tools1.revisit, tools1.eApply, tools1.eMedical, tools1.collectTo);
        };

        $('.container > .main').splitter({
            orientation: 'v',
            panel2Size: '40%',
        });

        const disableVideoCaptureTools = () => {
            const setCapturingStatusTool = toolbar2.option('items').find(tool => tool === tools.setCapturingStatus);
            if (setCapturingStatusTool) {
                setCapturingStatusTool.visible = false;
            }
            const showVideoWindowTool = toolbar2.option('items').find(tool => tool === tools.showVideoWindow);
            if (showVideoWindowTool) {
                showVideoWindowTool.visible = false;
            }
            toolbar2.repaint();
        };

        const refreshCapturingStatusTool = () => {
            if (supportVideoDevicePlugin) {
                const currentCapturingId = window.localStorage.getItem('current-video-capturing-id');
                if (currentCapturingId) {
                    setCapturingStatus(oid === currentCapturingId);
                } else {
                    setCapturingStatus(false);
                }
            }
        };

        const setCapturingStatus = (capturingStatus) => {
            const editing = getReportEditing();
            const tool = toolbar2.option('items').find(tool => tool === tools.setCapturingStatus);
            if (!editing || !supportVideoDevicePlugin) {
                tool.visible = false;
                toolbar2.repaint();
            } else if (isCapturing === null || isCapturing !== capturingStatus) {
                if (getReportEditing() && capturingStatus && tool) {
                    isCapturing = true;
                    tool.disabled = true;
                    tool.visible = true;
                    tool.options.text = '处于采集状态';
                    toolbar2.repaint();
                } else if (tool) {
                    isCapturing = false;
                    tool.disabled = false;
                    tool.visible = true;
                    tool.options.text = '设为采集状态';
                    toolbar2.repaint();
                }
            }
        }

        const tabPanel = $('.container > .main > .splitter > .resource-panels').dxTabPanel({
            tabsPosition: 'right',
            repaintChangesOnly: true,
            items: [
                {
                    title: '图像',
                    icon: '/icons/fa_image.svg',
                    template: '<div class="image-panel panel"/>',
                    visible: ris.verify("报告_图像")
                },
                {
                    title: '视频',
                    icon: '/icons/fa_video.svg',
                    template: '<div class="video-panlel panel"/>',
                    visible: ris.verify("报告_视频") && supportVideoDevicePlugin
                },
                {
                    title: '模板',
                    icon: '/icons/md_menu_book.svg',
                    template: '<div class="template-panel panel" />',
                    visible: ris.verify("报告_模板")
                },
                {
                    title: '历史',
                    icon: '/icons/md_history.svg',
                    template: '<div class="history-panel panel" />',
                    visible: ris.verify("报告_历史")
                },
                {
                    title: '单据',
                    icon: '/icons/fa_file_contract.svg',
                    template: '<div class="form-panel panel" />',
                    visible: ris.verify("报告_单据")
                },
                {
                    title: '事件',
                    icon: '/icons/md_event_note.svg',
                    template: '<div class="event-panel panel" />',
                    visible: ris.verify("报告_事件")
                },
                {
                    title: '备注',
                    icon: '/icons/md_speaker_notes.svg',
                    template: '<div class="remark-panel panel" />',
                    visible: ris.verify("报告_备注")
                },
                {
                    title: '队列',
                    icon: '/icons/x_exam_queuing.svg',
                    template: '<div class="queuing-panel panel" />',
                    visible: !!(ris.verify("报告_队列") && window.ris.getStationCode())
                },
                {
                    title: '检查',
                    icon: '/icons/x_exam_list.svg',
                    template: '<div class="exam-panel panel" />',
                    visible: ris.verify("报告_检查")
                },
            ],
            onItemRendered: e => {
                const $panel = $(e.itemElement).find('.panel');
                switch (e.itemData?.title) {
                    case '图像':
                        renderImagePanel($panel);
                        break;
                    case '视频':
                        renderVideoPanel($panel);
                        break;
                    case '模板':
                        renderTemplatePanel($panel);
                        break;
                    case '历史':
                        renderHistoryPanel($panel);
                        break;
                    case '单据':
                        renderFormPanel($panel);
                        break;
                    case '事件':
                        renderEventPanel($panel);
                        break;
                    case '备注':
                        renderRemarkPanel($panel);
                        break;
                    case '队列':
                        renderQueuingPanel($panel);
                        break;
                    case '检查':
                        renderExamPanel($panel);
                        break;
                }
            },
        }).dxTabPanel('instance');

        const form = $('.report-details').amisForm();
        const toolbar = $('.container > .toolbar').dxToolbar({ multiline: true }).dxToolbar('instance');
        const toolbar2 = $('.container > .toolbar2').dxToolbar({}).dxToolbar('instance');
        const tools = $.getReportTools($eventEmitter, null, null, null, form, [toolbar, toolbar2], {
            setCapturingStatus
        });

        ris.showLoading();

        Promise.all([$.get(`/api/report/getview/${oid}`), $.get(`/api/report/get-exam/${oid}`), $.get(`/api/report/image-quality-options?reportId=${oid}`)]).then(res => {
            ris.hideLoading();

            amisJosn = res[0].view;
            if (amisJosn && typeof amisJosn === 'string') {
                amisJosn = JSON.parse(amisJosn);
            }
            formData = res[1].data;
            document.title = `${formData.patient?.name ?? formData.accessionNumber ?? formData.patient?.patientId} | 报告`;
            if (formData.report.permissions.length === 0) {
                formData.report.isEditing = false;
            }
            let schema = formData.report.reportExtendingSchema;
            if (schema) {
                formData.report.reportExtendingSchema = JSON.parse(schema);
            }
            let extending = formData.report.reportExtending;
            if (extending) {
                formData.report.reportExtending = JSON.parse(extending);
            }
            formData.report.imageQulitayOptions = res[2];
            tools.updateToolbarItems(formData.report);
            form.updateView(amisJosn, formData);

            $('body > .container > .main .report-details').dxScrollView({
                scrollByContent: true,
                scrollByThumb: true,
            });

            $container.data('reportOid', oid);
            $container.data('reportEditing', formData.report.isEditing);
            $container.data('reportReadOnly', formData.report.readOnly);
            $container.trigger('onReportChanged', formData.report);

            if (formData.report.reportStatus === 8) {
                $('.main').addClass('audited');
            } else {
                $('.main').removeClass('audited');
            }

            const $reportSign = $('<div class="report-sign" />').appendTo($('.main.splitter-container > .splitter:first'));

            if (formData.isEmergency) {
                $('.main').addClass('emergency');
                $reportSign.append($('<div class="report-emergency">急诊</div>'));
            }

            if (formData.isShared && formData.sharedSign) {
                $('.main').addClass('shared');
                $reportSign.append($(`<div class="report-shared">${formData.sharedSign}</div>`));
            }

            if (supportVideoDevicePlugin) {
                setTimeout(async () => {
                    if (formData.report.isEditing) {
                        try {
                            const currentCapturingId = window.localStorage.getItem('current-video-capturing-id');
                            if (currentCapturingId === oid) {
                                setCapturingStatus(true);
                                window.chrome.webview.postMessage(JSON.stringify({
                                    type: 'current-capturing-study',
                                    data: oid
                                }));
                            } else {
                                const value = await ris.invokePlugin('VideoDevicePlugin', 'get-current-report-id', true, true);
                                setCapturingStatus(value === oid);
                            }
                        } catch (error) {
                            console.error(error);
                        }
                    } else {
                        setCapturingStatus(false);
                    }
                });

                setInterval(() => {
                    refreshCapturingStatusTool();
                }, 2000);
            }

        }).catch(() => {
            ris.hideLoading();
        });

        tools.print.options.items = [tools.formalPrint.options, tools.temporarilyPrint.options];
        //切换报告样式
        tools.changeReportStyle.options.dataSource = {
            load: () => {
                return $.get(`/api/get-${oid}-report-styles`)
            }
        }
        toolbar.option('items', [
            tools.save,
            tools.submit,
            tools.giveUpWrite,
            tools.complete,
            tools.revoke,
            tools.reject,
            tools.amend,
            tools.applyReview,
            tools.write,
            tools.audit,
            tools.viewImage,
            tools.print,
            tools.printReport2,
            tools.disassemble,
            tools.markFollowUp,
            tools.followUpRecord,
            tools.revisit,
            tools.eApply,
            tools.eMedical,
            tools.criticalValue,
            {
                ...tools.collectTo, options: {
                    ...tools.collectTo.options,
                    icon: 'like'
                }
            }
        ]);
        //切换报告样式
        tools.changeReportStyle.options.dataSource = {
            load: () => {
                return $.get(`/api/get-${oid}-report-styles`)
            },
            byKey(key, loadOptions) {
                return $.get(`/api/get-report-style-${key}`)
            }
        }
        toolbar2.option('items', [tools.reportStyle, tools.changeReportStyle, tools.showVideoWindow, tools.setCapturingStatus, tools.remake]);

        $container.on('onReportChanged', async () => {
            const editing = getReportEditing();

            const currentCapturingId = window.localStorage.getItem('current-video-capturing-id');
            if (currentCapturingId == oid && !editing) {
                window.localStorage.setItem('current-video-capturing-id', '');

                const result = await ris.ajax(`/api/report/${oid}/get-study-base-info`);
                const tempFile = await ris.host.writeFile('');
                await ris.invokePlugin('VideoDevicePlugin', `open "${result.data.deviceTypeCode}" "${tempFile}"`, true, true);

                window.chrome.webview.postMessage(JSON.stringify({
                    type: 'current-capturing-study'
                }));
            }

            if (supportVideoDevicePlugin) {
                refreshCapturingStatusTool();
            }

            if (reportImageList) {
                reportImageList.setReadOnly(!editing);
            }

            if (reportVideoList) {
                reportVideoList.setReadOnly(!editing);
            }

            for (const diagnosisTemplate of diagnosisTemplates) {
                diagnosisTemplate.setReadOnly(!editing);
            }
        });

        if (supportVideoDevicePlugin) {
            window.chrome.webview.addEventListener("message", (event) => {
                const message = JSON.parse(event.data);
                if (message.type === 'current-capturing-study') {
                    setCapturingStatus(message.data === oid);
                }
            });
        } else {
            disableVideoCaptureTools();
        }

        setTimeout(() => {
            // 添加审核通过印章
            $('<img class="report-audited" src="/images/report-audited.png" />').appendTo($('.main.splitter-container > .splitter:first'));
        });

        // 添加tabIndex
        const intervalId = setInterval(() => {
            const reportDetails = document.getElementsByClassName('report-details')[0];
            const amisForm = reportDetails.getElementsByClassName('cxd-Form');
            if (amisForm && amisForm.length > 0) {
                let inputs = $(".report-table .input-item").toArray()
                    .map((ele, index) => {
                        const $ele = $(ele);
                        const classNames = $(ele).attr('class').split(' ');
                        let tabindex = (index * 100) + 10000;
                        for (const className of classNames) {
                            if (className.indexOf('tabindex-') === 0) {
                                tabindex = className.slice('tabindex-'.length);
                            }
                        }
                        return { tabindex, $input: $ele.find('input') };
                    })
                    .filter(x => x.$input.length > 0)
                    .sort((a, b) => a.tabindex - b.tabindex);

                inputs.forEach(({ tabindex, $input }) => {
                    $input.attr('tabindex', tabindex);
                    $input.on('keydown', e => {
                        if (e.keyCode === 13) {
                            let input = inputs.find(x => x.$input.get(0) === e.target);
                            input = inputs[(inputs.indexOf(input) + 1)];
                            if (input) {
                                input.$input.focus();
                            }
                        }
                    });
                });

                clearInterval(intervalId);
            }
        }, 500);
    });
})();